<?php

namespace App\Jobs;

use App\Models\Addressee;
use App\Models\MsgTask;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\DB;

class SynRebuild implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    private $msg_task_id;
    public function __construct($msg_task_id =0)
    {
        //
        $this->msg_task_id = $msg_task_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $redis = app('redis');
        $redis -> del("msgTask:enable-account");
        if($this->msg_task_id){
            $msgTask = MsgTask::where('id',$this->msg_task_id) -> with("sendLog") ->  get();
        }else{
            $msgTask = MsgTask::where("status" , "<" , 2)->where("enable",1) ->whereNull('file_column')-> with("sendLog")-> get();
        }
        // 所有可用账号
        $addressee = Addressee::where("status" , 0) -> get() -> pluck("number");
        //如果账号不为空   就加入到redis
        if($addressee -> isNotEmpty()){
            $addressee =$addressee -> toArray();
            $addressee = array_chunk($addressee, 2000);
            $redis->pipeline(function ($pipe) use ($addressee){
                foreach ($addressee as $item){
                    $pipe->sadd("msgTask:enable-account", ...$item);
                }
            });
        }
        //循环
        $msgTask -> each(function (MsgTask $msgTask) use ($redis){
            $msg_task_id = $msgTask -> id;
            $key = "msg:app-enable-account:{$msg_task_id}";
            $sendKey = "msg:send-log:{$msg_task_id}";
            $redis->del([$sendKey]);
            $sendLog = $msgTask -> sendLog -> pluck("addressee");
            if($sendLog -> isNotEmpty()){
                $redis -> srem($sendKey , $sendLog -> toArray());
            }
            $redis -> sdiffstore($key , "msgTask:enable-account" , $sendKey);
        });


    }
}
